package bueu.bexl;

import static bueu.bexl.utils.TypeUtils.booleanValue;

public class ConditionalExpr extends BexlExpr {

	private final BexlExpr condExpr;
	private final BexlExpr thenExpr;
	private final BexlExpr elseExpr;

	public ConditionalExpr(final BexlExpr condExpr, final BexlExpr thenExpr, final BexlExpr elseExpr) {
		super(condExpr.isRelative() || thenExpr.isRelative() || elseExpr.isRelative());
		this.condExpr = condExpr;
		this.thenExpr = thenExpr;
		this.elseExpr = elseExpr;
	}

	public BexlExpr getCondExpr() {
		return this.condExpr;
	}

	public BexlExpr getThenExpr() {
		return this.thenExpr;
	}

	public BexlExpr getElseExpr() {
		return this.elseExpr;
	}

	@Override
	protected final Object eval(final BexlCtx ctx, final Object current, final boolean set,
			final Object newValue) throws BexlException {
		
		if (booleanValue(this.condExpr.eval(ctx, current, set, newValue))) {
			return this.thenExpr.eval(ctx, current, set, newValue);
		}

		return this.elseExpr.eval(ctx, current, set, newValue);
	}
	
	@Override
	public final String toString() {
		StringBuilder sb = new StringBuilder("(");
		sb.append(this.condExpr);
		sb.append(" ? ");
		sb.append(this.thenExpr);
		sb.append(" : ");
		sb.append(this.elseExpr);
		sb.append(')');
		
		return sb.toString();
	}
}
